<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Http\Resources\ContentResource;
use App\Models\Content;
use App\Models\Position;
use Illuminate\Http\Request;

class ContentController extends ApiController
{
    /**
     * Display a listing of the resource.
     *
     */
    public function index(Request $request)
    {
        $userId = app('userId');
        $page_size = $request->input('page_size', 20);
        $search = $request->input('search');
        $type = $request->input('type');
        $owner = $request->input('owner');
        $collect = $request->input('collect');
        if (!$userId) {
            if ($owner || $collect) {
                return $this->okReturn([
                    'pagination' => [
                        'page' => 1,
                        'page_size' => 10,
                        'total' => 0,
                    ],
                    'result' => [],
                ]);
            }
        }

        $list = Content::with(['user', 'userCollections', 'userOrders', 'position'])
        ->when(isset($type), function($query) use ($type) {
            $query->where('type', intval($type));
        })->when($owner, function($query) use ($userId) {
            $query->where('user_id', $userId);
        }, function($query) {
            $query->enabled();
        })->when($collect, function($query) use ($userId) {
            $query->whereHas('userCollections', function($query) use ($userId) {
                $query->where('user_id', $userId);
            });
        })->when($search, function($query, $search) {
            $query->where('title', 'LIKE', '%' . $search . '%')
                ->orWhere('descrition', 'LIKE', '%' . $search . '%')
                ->orWhere('address', 'LIKE', '%' . $search . '%')
                ->orWhere('tags', 'LIKE', '%' . $search . '%');
        })
        ->orderByRaw('refresh_at DESC, created_at DESC')
        ->paginate($page_size);

        $result = $list->map(function($item) {
            return new ContentResource($item);
        });

        return $this->okReturn([
            'pagination' => [
                'page' => $list->currentPage(),
                'page_size' => intval($page_size),
                'total' => $list->total(),
            ],
            'result' => $result,
        ]);

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    public function store(Request $request)
    {
        $userId = app('userId');
        if (!$userId)  {
            return $this->errorReturn('请先登录');
        }
        $title = $request->input('title');
        $descrition = $request->input('descrition');
        $type = $request->input('type');
        $is_charge = $request->input('is_charge');
        $tags = $request->input('tags');
        $mobile = $request->input('mobile');
        $position_id = $request->input('position_id');
        $images = $request->input('images');
        $address = $request->input('address');
        $longitude = $request->input('longitude');
        $latitude = $request->input('latitude');

        if (!empty($images)) {
            foreach ($images as &$img) {
                $img = str_replace('/storage/', '', $img);
            }
        }

        $content = new Content([
            'title' => trim($title),
            'user_id' => $userId,
            'descrition' => trim($descrition),
            'mobile' => trim($mobile),
            'images' => $images,
            'address' => trim($address),
            'longitude' => doubleval($longitude),
            'latitude' => doubleval($latitude),
            'type' => intval($type),
            'position_id' => intval($position_id),
            'is_charge' => intval($is_charge),
            'tags' => $tags,
        ]);

        if ($content->save()) {
            return $this->okReturn($content->id);
        }

        return $this->errorReturn('发布失败');

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Content  $content
     */
    public function show(Content $content)
    {
        $result = new ContentResource($content);
        return $this->okReturn($result);
    }

    /**获取所有职位 */
    public function getPositions()
    {
        return $this->okReturn(Position::select(['id', 'name'])->get());
    }

    /**刷新内容 */
    public function refreshContent(Request $request)
    {
        $content_id = $request->input('content_id');

        if (empty($content_id)) {
            return $this->errorReturn('param error');
        }
        $userId = app('userId');
        if (!$userId) {
            return $this->errorReturn('请先登录');
        }

        $content = Content::find($content_id);
        if (empty($content->id)) {
            return $this->errorReturn('找不到内容');
        }
        if ($content->user_id != $userId) {
            return $this->errorReturn('没有权限刷新');
        }
        if ($content->refresh()) {
            return $this->okReturn([]);
        }
        return $this->errorReturn('刷新内容失败');
    }
}
